package com.example.studentsRoom.controller;


import com.example.studentsRoom.entity.Dormitory;
import com.example.studentsRoom.entity.Student;
import com.example.studentsRoom.form.SearchForm;
import com.example.studentsRoom.service.impl.DormitoryService;
import com.example.studentsRoom.service.impl.StudentService;
import com.example.studentsRoom.util.ResultUtil;
import com.example.studentsRoom.vo.PageVo;
import com.example.studentsRoom.vo.ResultVo;
import com.example.studentsRoom.vo.StudentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2022-07-19
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private DormitoryService dormitoryService;

    @GetMapping("/save")
    public ResultVo save(Student student){
        Boolean saveStudent = studentService.saveStudent(student);
        if (!saveStudent){
            return ResultUtil.failed();
        }
        return ResultUtil.success(null);
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list/{page}/{size}")
    public ResultVo list(
            @PathVariable("page") Integer page,
            @PathVariable("size") Integer size
    ){
        PageVo list=studentService.listPage(page,size);
        return ResultUtil.success(list);
    }

    /**
     * 模糊查询+分页
     * @param searchForm
     * @return
     */
    @GetMapping("/search")
    public ResultVo search(SearchForm searchForm){
        PageVo pageVo=studentService.search(searchForm);
        return ResultUtil.success(pageVo);
    }

    /**
     * 根据id来查数据
     * @param id
     * @return
     */
    @GetMapping("/findById/{id}")
    public ResultVo findById(@PathVariable("id") String id){
        Student student = studentService.getById(id);

        Dormitory dormitory = dormitoryService.getById(student.getDorId());

        StudentVo studentVo=new StudentVo();
        BeanUtils.copyProperties(student,studentVo);
        studentVo.setBId(dormitory.getBId());
        studentVo.setOldDorId(dormitory.getDorId());

        return ResultUtil.success(studentVo);
    }

    /**
     * 更新操作
     * @param student
     * @return
     */
    @GetMapping("/upDate")
    public ResultVo upDate(StudentVo student){
        Boolean update = studentService.update(student);
        if (!update) return ResultUtil.failed();
        return ResultUtil.success(null);
    }

    /**
     * 删除学生
     * @param id
     * @return
     */
    @DeleteMapping("/deleteById/{id}")
    public ResultVo deleteById(@PathVariable("id") String id){
        Boolean delete = studentService.deleteById(id);
        if (delete){
            return ResultUtil.success(null);
        }else return ResultUtil.failed();
    }
}

